from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthUser
from oauth.serializers import QQAuthUserSerializer
from oauth.utils import generate_save_user_token


class QQAuthURLView(APIView):
    """
    一个专门针对URL的类
    """
    def get(self, request):
        # 登录成功以后的跳转地址
        next = request.query_params.get('next')
        if next is None:
            # 如果没有设置，则默认为域名根目录
            next = '/'

        # 使用QQLoginTool 工具包里面的方法生成url
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        login_url = oauth.get_qq_url()

        return Response({'login_url': login_url})


class QQAuthUserView(APIView):
    """
    用户鉴权类
    """

    def get(self, request):
        # 1. 获取code授权码
        code = request.query_params.get('code')
        if code is None:
            return Response({'message': '缺少code授权码'}, status=status.HTTP_400_BAD_REQUEST)
        # 2. 获取QQ登录的access_token
        # 使用qqLoginTool 工具包里面的方法生成url
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        access_token = oauth.get_access_token(code)
        # 3. 根据access_token 获取openID
        openid = oauth.get_open_id(access_token)
        # 4.根据openID到数据库中查找是否有对应QQ的用户
        try:
            oauth_user = OAuthUser.objects.get(openid=openid)
        except OAuthUser.DoesNotExist:
            return Response({
                'access_token': generate_save_user_token(openid),
            })
        else:
            # 如果openid 已经绑定美多商城用户，直接生成JWT_token, 并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 获取oauth_user 关联的user
            user = oauth_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            response = merge_cart_cookie_to_redis(request, user, response)

            return response

    def post(self, request):
        # 获取序列化器对象
        serializer = QQAuthUserSerializer(data=request.data)
        # 校验数据
        # print(request.data)
        serializer.is_valid(raise_exception=True)
        # 调用了序列化器中的save
        user = serializer.save()

        # 5.返回登录状态jwt
        # 如果openid已绑定商城用户，直接生成JWT TOEKN并返回
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 获取oauth_user关联的user
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username,
        })

        response = merge_cart_cookie_to_redis(request, user, response)

        return response
